//
//  NHUtils.m
//  MUBATE
//
//  Created by sunbin on 2017/2/14.
//  Copyright © 2017年 Quanli. All rights reserved.
//

#import "NHUtils.h"
#import <MobileCoreServices/MobileCoreServices.h>

@implementation NHUtils

+ (void)setButton:(UIButton *)btn isLaunch:(BOOL)launch setTitle:(NSString *)title setLayerCornerRadius:(CGFloat)radius setFont:(CGFloat)Fon{
    // 设置标题
    [btn setTitle:title forState:UIControlStateNormal];
    // 设置圆角
    [btn setLayerCornerRadius:radius borderWidth:0 borderColor:[UIColor clearColor]];
    // 查看状态
    // 设置背景色 文字颜色
    [btn setBackgroundColor:launch?[UIColor BtnStateNormalBackgroundColor]:[UIColor appBtnStateNormalBackgroundColor] forState:UIControlStateNormal];
    [btn setBackgroundColor:launch?[UIColor BtnStateDisabledBackgroundColor]:[UIColor appBtnStateDisabledBackgroundColor] forState:UIControlStateDisabled];
    
    [btn setTitleColor:launch?[UIColor BtnStateNormalTitleColor]:[UIColor appBtnStateNormalTitleColor] forState:UIControlStateNormal];
    [btn setTitleColor:launch?[UIColor BtnStateDisabledTitleColor]:[UIColor appBtnStateDisabledTitleColor] forState:UIControlStateDisabled];
    
    // 设置字号  字体
    btn.titleLabel.font = launch?FONT_FONTFZHeiB01S(Fon):FONT_FONTMicrosoftYaHei(Fon);
    }


// 加载自定义xib view
+ (UIView *)loadViewFormCtl:(UIViewController *)ctl view:(UIView *)view{
    view.frame = SCREEN_RECT;
    [ctl.view addSubview:view];
    return view;
}


+ (void)saveCookies
{
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject: cookiesData forKey: @"sessionCookies"];
    [defaults synchronize];
    
}


+ (void)setLabel:(UILabel *)label text:(NSString *)text textColor:(UIColor *)alertTextColor font:(CGFloat)size{
    label.text =  text;
    label.textColor = alertTextColor;
    label.font = FONT_FONTFZHeiB01S(size);
}



/**
 *  判断字符串是否为空
 */
+ (BOOL)isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;}
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;}
    if ([string isKindOfClass:[NSDictionary class]]) {
        return YES;}
    if ([string isKindOfClass:[NSString class]] == NO) {
        return YES;}
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        return YES;}
    if ([string isEqualToString:@""]) {
        return YES;}
    return NO;
}

+ (NSString *)validString:(NSString *)string {
    if ([self isBlankString:string]) {
        return  @"";
    } else {
        return string;}
}



+ (void)presentViewController:(NSString *)className ctl:(UIViewController *)ctl animationType:(WXSTransitionAnimationType)animationType isSysBackAnimation:(BOOL)isSysBackAnimation{

    Class class = NSClassFromString(className);
    UIViewController *controller = [[class alloc] init];
    
    [ctl wxs_presentViewController:controller makeTransition:^(WXSTransitionProperty *transition) {
        transition.animationType = animationType;
        transition.isSysBackAnimation = isSysBackAnimation;
    } completion:nil];
}


+ (void)setCountDown:(UIButton *)btn setLayerCornerRadius:(CGFloat)radius borderWidth:(CGFloat)width borderColor:(UIColor *)borderColor setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state{
    [btn setLayerCornerRadius:radius borderWidth:width borderColor:borderColor];
    [btn setBackgroundColor:backgroundColor forState:state];

}



+ (void) alertAction:(SEL)selector alertControllerWithTitle:(NSString *)Title Message:(NSString *)message Vctl:(UIViewController *)Ctl Cancel:(BOOL)isCancel
{
    UIAlertController *alertCtl = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%@",@"确定"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [Ctl performSelector:selector withObject:Ctl afterDelay:0.1];
    }];
    [alertCtl addAction:defaultAction];
    
    if (isCancel) {
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%@",@"取消"] style:UIAlertActionStyleCancel handler:nil];
        [alertCtl addAction:cancelAction];
    }else{}
    [Ctl presentViewController:alertCtl animated:YES completion:^{
        
    }];
}




+ (void)imagePickerPermissions:(UIViewController *)ctl didClickedButtonAtIndex:(NSInteger)index{
    if (index == 0) {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [CommonUtils showAlertWithTaget:ctl andMsg:@"Device has no camera"];
        } else {
            //相机
            UIImagePickerController *imagePickerController = [UIImagePickerController new];
            imagePickerController.delegate = ctl;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.allowsEditing = YES;
            imagePickerController.showsCameraControls = YES;
            imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
            [ctl presentViewController:imagePickerController animated:YES completion:nil];
        }
        return;
    }
    
    if (index == 1) {
        //相册
        UIImagePickerController *imagePickerController = [UIImagePickerController new];
        imagePickerController.delegate = ctl;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerController.allowsEditing = YES;
        imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        [ctl presentViewController:imagePickerController animated:YES completion:nil];
        return;
    }
}


// *  对图片尺寸进行压缩--

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (void)updatePortrait:(NSArray *)images name:(NSString *)name mimeType:(NSString *)mimeType upDataSucceed:(UPDatePortraitSuccessful)succeed upDataFail:(UPDatePortraitFail)fail{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
    
    NSDictionary *paramer = @{@"uid":@([YConfig getOwnID]),
                              @"sign":SIGN };

    [ZL_NetworkHelper uploadWithURL:HEADPIC parameters:paramer images:images name:name fileName:fileName mimeType:mimeType progress:^(NSProgress *progress) {
    } success:^(id responseObject) {
        NSString *res = IF_NULL_TO_STRING([responseObject objectForKey:@"res"]);
        NSString *msg = IF_NULL_TO_STRING([responseObject objectForKey:@"msg"]);
        if ([res isEqualToString:@"1"]) {
            NSString *url = IF_NULL_TO_STRING([responseObject objectForKey:@"url"]);
            succeed(msg ,url);
        }else{
            fail(msg);
        }
    } failure:^(NSError *error) {
        fail(error.localizedDescription);
    }];


}



#pragma make 微博分享
// 发布纯文本
+ (void)shareSinaWeiboWithText:(NSString *)text {
    if (![WeiboSDK isWeiboAppInstalled]) {
        
        NSLog(@"未安装");
    }else {
        
        WBMessageObject *message = [WBMessageObject message];
        message.text = text;
        
        WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
        [WeiboSDK sendRequest:request];
    }
    
}

// 发布图片文字等。
+ (void)shareSinaWeiboWithText:(NSString *)text image:(UIImage *)image{
    if (![WeiboSDK isWeiboAppInstalled]) {
        NSLog(@"未安装");
        
    }else {
        WBMessageObject *message = [WBMessageObject message];
        message.text = text;
        
        // 消息的图片内容中，图片数据不能为空并且大小不能超过10M
        WBImageObject *imageObject = [WBImageObject object];
        imageObject.imageData = UIImageJPEGRepresentation(image, 1.0);
        message.imageObject = imageObject;
        
        WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
        [WeiboSDK sendRequest:request];
    }
    
}



// 核实密码是否符合要求
+ (pwdErrorType)enterPwd:(NSString *)newPwd resentPwd:(NSString *)resentPwd{
    pwdErrorType ty;
    
    //判断 两密码是否相同
    //1.两者相同 且不为空
    if (![NHUtils isBlankString:newPwd] && [newPwd isEqualToString:resentPwd]) {
        //2.密码格式要求
        if ([newPwd checkPassWord]) {
            // 正确
            ty = NOError;
            
        }else{
            //错误 密码格式错误
            ty = FormatError;
        }
    }else{
        //不相同
        ty = Unequally;
    }
    return ty;
}

#pragma make -颜色转图片
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size alpha:(float)alpha
{
    @autoreleasepool {
        
        CGRect rect = CGRectMake(0, 0, size.width, size.height);
        
        UIGraphicsBeginImageContext(rect.size);
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetAlpha(context, alpha);
        CGContextSetFillColorWithColor(context,color.CGColor);
        CGContextFillRect(context, rect);
        
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return img;
        
    }
}

+ (BOOL)isPhoneLog{
    NSString *account = [[YConfig getOwnAccountAndPassword] firstObject];
    BOOL isPhoneLog;
    if (![account isEmailAddress]) {
        isPhoneLog = YES;
    }else{
        isPhoneLog = NO;
    }
    return isPhoneLog;
}


+ (BOOL)isAccount:(NSString *)account accountTy:(bingTy)ty{
    
    switch (ty) {
        case bingPhone:return [account isMobileNumberClassification];
            break;
        case bingEmaill:{
            // 邮箱长度限制6-12.@qq.com
            NSString *prefix = [[account componentsSeparatedByString:@"."] firstObject];
            NSUInteger atIndex = prefix.length;
            return [account isEmailAddress] && (atIndex > 5 && atIndex < 13);
        };
            break;
        default:
            break;
    }}


+ (void)pushAndPop:(NSString *)popView range:(NSRange )makeRange currentCtl:(UIViewController *)wSelf{
    Class class = NSClassFromString(popView);
    NSArray *ctlAry = [wSelf.navigationController viewControllers];
    [ctlAry enumerateObjectsUsingBlock:^(UIViewController *Ctl, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([Ctl isKindOfClass:class]) {
            NSMutableArray *array = [wSelf.navigationController.viewControllers mutableCopy];
            [array removeObjectsInRange:makeRange];
            
            [wSelf.navigationController setViewControllers:[array copy] animated:YES];
        }
    }];
}





+ (UIImage *)generateQrCode:(NSString *)qrCodeContent qrCodeAdress:(NSString *)qrCodeAdress qrCodeColorwithRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue qrCodeSize:(CGFloat)qrCodeSize{
    
    
    UIImage *qrcode = [self createNonInterpolatedUIImageFormCIImage:[self createQRForString:[qrCodeAdress stringByAppendingString:[NSString stringWithFormat:@" %@" ,qrCodeContent]]] withSize:qrCodeSize];
    
    UIImage *customQrcode = [self imageBlackToTransparent:qrcode withRed:red andGreen:green andBlue:blue];
    return customQrcode;
}



+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // create a bitmap image that we'll draw into a bitmap context at the desired size;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // Create an image with the contents of our bitmap
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    // Cleanup
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}
#pragma mark - QRCodeGenerator
+ (CIImage *)createQRForString:(NSString *)qrString {
    // Need to convert the string to a UTF-8 encoded NSData object
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    // Create the filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // Set the message content and error-correction level
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    // Send the image back
    return qrFilter.outputImage;
}
#pragma mark - imageToTransparent

+ (UIImage*)imageBlackToTransparent:(UIImage*)image withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue{
    const int imageWidth = image.size.width;
    const int imageHeight = image.size.height;
    size_t      bytesPerRow = imageWidth * 4;
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    // create context
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    // traverse pixe
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++){
        if ((*pCurPtr & 0xFFFFFF00) < 0x99999900){
            // change color
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[3] = red; //0~255
            ptr[2] = green;
            ptr[1] = blue;
        }else{
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[0] = 0;
        }
    }
    // context to image
    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
                                        kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
                                        NULL, true, kCGRenderingIntentDefault);
    CGDataProviderRelease(dataProvider);
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
    // release
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return resultUIImage;
}


#pragma mark - imageToTransparent
void ProviderReleaseData (void *info, const void *data, size_t size){
    free((void*)data);
}




+ (NSString *)moneyWithInterge:(CGFloat)moneValue{
    NSString *account;
    if (moneValue == 0) {
        account = [NSString stringWithFormat:@"%.1f" ,moneValue];
    }
    if (moneValue >0 && moneValue <= 0.01) {
        account =@"≤0.01";
    }
    if (1.0 > moneValue && moneValue> 0.01) {
        account = [NSString stringWithFormat:@"%.2f" ,moneValue];
    }
    if (100.0 > moneValue && moneValue >= 1.0) {
        account = [NSString stringWithFormat:@"%.2f" ,moneValue];
    }
    if (1000.0 > moneValue && moneValue >= 100.0) {
        account = [NSString stringWithFormat:@"%.1f" ,moneValue];
    }
    if (10000.0 > moneValue && moneValue >= 1000.0) {
        account = [NSString stringWithFormat:@"%.2f千" ,moneValue/1000];
    }
    if (10000000.0 > moneValue && moneValue>= 10000.0) {
        account = [NSString stringWithFormat:@"%.2f万" ,moneValue/10000];
    }
    return account;
}











+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}









//逆向遍历
+(NSMutableArray *)flashbackAry:(NSArray *)array{
    NSEnumerator *enumerator = [array reverseObjectEnumerator];    
    return [[NSMutableArray alloc] initWithArray:[enumerator allObjects]];
}

















+(BOOL)isEqualToAry:(NSMutableArray *)oldArr newArr:(NSMutableArray *)newArr{

    bool bol = false;
    //对数组1排序。
    [oldArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return obj1 > obj2;
    }];
    
    ////上个排序好像不起作用，应采用下面这个
    [oldArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2){return [obj1 localizedStandardCompare: obj2];}];
    
    //对数组2排序。
    [newArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return obj1 > obj2;
    }];
    ////上个排序好像不起作用，应采用下面这个
    [newArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2){return [obj1 localizedStandardCompare: obj2];}];
    
    
    if (newArr.count == oldArr.count) {
        
        bol = true;
        for (int16_t i = 0; i < oldArr.count; i++) {
            
            id c1 = [oldArr objectAtIndex:i];
            id newc = [newArr objectAtIndex:i];
            
            if (![newc isEqualToString:c1]) {
                bol = false;
                break; 
            } 
        } 
    } 
    
    if (bol) {  NSLog(@"两个数组的内容相同！");}else {  NSLog(@"两个数组的内容不相同！");    }

    return bol;
}



+ (void)clear{
    
    // 删除数据库表
    BQLDBTool *tool =  [BQLDBTool instantiateTool];

    if([tool deleteDataWith:NewMessageFile]) {NSLog(@"删除成功");}
    else {NSLog(@"删除失败");}

    [[SDImageCache sharedImageCache] clearMemory];
    
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
    }];
    [ZL_NetworkCache removeAllHttpCache];
}



@end
